<template>
    <div
        :class="['w-full p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <!-- 顶部 -->
        <PageHeader :title="PageType[pageType]" :show-refresh="false">
            <template #custom>
                <!-- 查看模式 - 只有返回按钮 -->
                <template v-if="isDisabled">
                    <el-button round type="primary" @click="cancel">返回</el-button>
                </template>
                <!-- 新增模式 - 返回、保存草稿、确认发布 -->
                <template v-if="pageType !== 'see'">
                    <el-button round @click="cancel">取消</el-button>
                    <el-button round type="primary" @click="submitForm(ruleFormRef, 'save')">确认</el-button>
                </template>
            </template>
        </PageHeader>
        <template v-if="!isLoading">
            <!-- 表单 -->
            <div class="w-full flex-between-items-box">
                <!-- 活动设置  join-member-wrapper-->
                <div class="h-full card-style common-shadow w-full relative min-content-header-height">
                    <div class="card-title mb-30 w-full flex-between-items-box">
                        <span>活动设置</span>
                        <Icon
                            name="Edit"
                            :class="['cursor-pointer', isEdit ? 'text-primary' : 'text-t-default']"
                            :size="20"
                            @click="isEdit = true"
                        />
                    </div>
                    <!-- 表单 -->
                    <el-form
                        class="flex-col"
                        ref="ruleFormRef"
                        :model="ruleForm"
                        :rules="rules"
                        :disabled="!isEdit"
                        label-width="100px"
                        status-icon
                    >
                        <!-- 活动规则 -->
                        <el-col :span="10">
                            <el-form-item label="活动名称：" prop="articleTitle">
                                <el-input v-model="ruleForm.articleTitle"/>
                            </el-form-item>
                        </el-col>
                        <!-- 活动时间 -->
                        <el-col :span="8">
                            <el-form-item label="活动时间：" prop="articleTitle">
                                <el-date-picker
                                    class="w-full"
                                    v-model="ruleForm.timeRangeValue"
                                    clearable
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="起始时间"
                                    end-placeholder="结束时间"
                                />
                            </el-form-item>
                        </el-col>
                        <!-- 活动对象 -->
                        <el-col :span="12">
                            <el-form-item label="销售指标：">
                                <div class="sale-box flex-between-items-box w-5/6">
                                    <div class="sale-box-left flex-col justify-between h-full">
                                        <div class="sale-box-top">指标名称</div>
                                        <el-radio label="1" size="large">GMV</el-radio>
                                        <el-radio label="1" size="large">销售金额</el-radio>
                                    </div>
                                    <div class="sale-box-left h-full flex-1">
                                        <div class="sale-box-top">指标描述</div>
                                        <div class="sale-box-middle">总交易额，包含有效、无效订单额度累计总和</div>
                                        <div class="sale-box-bottom">完成支付的订单额度累计总和</div>
                                    </div>
                                    <div class="sale-box-left h-full">
                                        <div class="sale-box-top">活动目标</div>
                                        <div class="sale-box-middle">
                                            <el-input/>
                                            <div class="ml-10" style="width: 50px;">万元</div>
                                        </div>
                                        <div class="sale-box-bottom">
                                            <el-input/>
                                            <div class="ml-10" style="width: 50px;">万元</div>
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                            <!-- 用户指标 -->
                            <el-form-item label="用户指标：">
                                <div class="sale-box flex-between-items-box w-5/6">
                                    <div class="sale-box-left flex-col justify-between h-full">
                                        <div class="sale-box-top">指标名称</div>
                                        <el-radio label="1" size="large">新客数</el-radio>
                                        <el-radio label="1" size="large">参与用户数</el-radio>
                                    </div>
                                    <div class="sale-box-left h-full flex-1">
                                        <div class="sale-box-top">指标描述</div>
                                        <div class="sale-box-middle">历史时间未下单的用户</div>
                                        <div class="sale-box-bottom">参与活动的下单用户总数</div>
                                    </div>
                                    <div class="sale-box-left h-full">
                                        <div class="sale-box-top">活动目标</div>
                                        <div class="sale-box-middle">
                                            <el-input/>
                                            <div class="ml-10" style="width: 50px;">人</div>
                                        </div>
                                        <div class="sale-box-bottom">
                                            <el-input/>
                                            <div class="ml-10" style="width: 50px;">人</div>
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>

                    </el-form>
                </div>
                <!-- 活动渠道 -->
                <!--                <div class="min-content-header-height join-member-wrapper card-style common-shadow">-->
                <!--                    <div class="card-title mb-30 w-full flex-between-items-box">-->
                <!--                        <span>活动渠道</span>-->
                <!--                        <Icon name="Refresh" class="cursor-pointer text-t-default" :size="20"/>-->
                <!--                    </div>-->
                <!--                </div>-->
            </div>
        </template>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ArticleDetail, ArticleParams, httpAddArticle, httpUpdateArticle } from '@api/module/brandPromotion'
import { ElMessages, FormRule, timeout } from '@utils/methods'
import Icon from '@/components/Icon/index.vue'
import dayjs from 'dayjs'
import PageHeader from '@components/PageHeader/index.vue'

const router = useRouter()
const { query } = useRoute()

// 页面加载
const isLoading = ref(true)

// 页面标题类型
enum PageType {
    'add' = '新增活动',
    'edit' = '编辑活动',
    'see' = '活动详情'
}

// 获取 enum 的 key 值
type PageTypeKey = keyof typeof PageType

// 是否禁用表单
const isDisabled = computed(() => pageType.value === 'see')

// 是否显示返回按钮
const pageType = ref<PageTypeKey>()

// 编辑活动 id
const activityId = ref()

// 页面初始化
const pageInit = async () => {
    pageType.value = <PageTypeKey>query.pageType
    switch (query.pageType) {
    case 'add':
        await timeout(500)
        isLoading.value = false
        break
    default:
        activityId.value = Number(query.articleId)
        await getArticleDetail()
    }
}

pageInit()

// 是否编辑
const isEdit = ref(false)

// 表单实例
const ruleFormRef = ref<FormInstance>()

// 表单数据
const ruleForm = reactive<any>({
    activityDesc: '',
    isNotice: false,
    activityGift: null,
    timeRangeValue: [],
    radioValue: ''
})

// 表单校验
const rules = <FormRules>{
    activityDesc: [FormRule.requireRule('请输入活动描述')],
    articleContent: [FormRule.requireRule('请输入文章内容')],
    articlePictureList: [FormRule.requireRule('请上传文章图片')]
}

const tableData = [
    {
        memberCardId: 'X0000113',
        userPhone: '18831845005',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000112',
        userPhone: '14779427242',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000111',
        userPhone: '18283189711',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000110',
        userPhone: '14737366601',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    },
    {
        memberCardId: 'X0000109',
        userPhone: '14737366601',
        distributeGifts: '20 积分',
        distributionTime: '2023-04-21 22:29:56'
    }
]

// 近 7 日发放量变化
const sevenDayFlowOptions = ref({})
// 文章详情
const articleDetail = ref<ArticleDetail>()

setTimeout(async () => {
    await timeout(500)
    await nextTick()
    /**
     * 近 7 日访问流量
     * */
    // 近 7 日日期
    const sevenDay = []
    for (let day = 0; day <= 6; day++) {
        sevenDay.push(dayjs().subtract(day, 'day').format('MM-DD'))
    }
    sevenDayFlowOptions.value = {
        // 提示框
        tooltip: {
            trigger: 'item'
        },
        xAxis: {
            type: 'category',
            data: sevenDay.reverse()
        },
        yAxis: {
            type: 'value',
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        series: [
            {
                data: [4522, 3841, 6649, 7724, 4342, 3387, 3112],
                type: 'line',
                smooth: true
            }
        ]
    }
}, 200)

// 获取文章详情 编辑 / 详情
const getArticleDetail = () => {
    isLoading.value = false
    // httpArticleDetail({
    //     articleId: 1
    // }).then(({ success, data }) => {
    //     if (success) {
    //         articleDetail.value = data
    //         const { articleTitle, articleContent, articlePictureList } = data
    //         ruleForm.articleTitle = articleTitle
    //         ruleForm.articleContent = articleContent.replaceAll('\\n', '<br/>')
    //         ruleForm.articlePictureList = articlePictureList
    //     }
    // }).finally(async () => {
    //     await timeout(500)
    //     isLoading.value = false
    // })
}

getArticleDetail()

// 取消
const cancel = () => {
    router.back()
}

// 提交表单参数
type SubmitForm = (formEl: FormInstance | undefined, type: 'save' | 'release') => void

// 提交表单
const submitForm: SubmitForm = async (formEl, type) => {
    if (!formEl) return
    await formEl.validate(valid => {
        if (valid) {
            // pageType.value === 'add' ? addArticle(type) : updateArticle(type)
        }
    })
}

// 新增文章
const addArticle = (type: 'save' | 'release') => {
    const { articleTitle, articleContent, author, articlePictureList } = ruleForm
    // 请求参数
    const params: ArticleParams = {
        articleTitle,
        articleContent,
        author,
        releaseStatus: type === 'save' ? 0 : 1,
        articlePictureList: articlePictureList.map((item: any) => ({
            name: item.name,
            url: item.response.data
        }))
    }
    // 文章添加
    httpAddArticle(params).then(({ success }) => {
        if (success) {
            ElMessages.success('新增成功！')
            cancel()
        } else {
            ElMessages.warning('新增失败！')
        }
    })
}

// 更新文章 保存草稿 | 确认发布
const updateArticle = (type: 'save' | 'release') => {
    const { articleTitle, articleContent, articlePictureList } = ruleForm
    // 更新数据
    const updateParams = {
        ...articleDetail.value,
        articleTitle,
        articleContent,
        createdTime: dayjs(articleDetail.value?.createdTime).format('YYYY-MM-DD HH:mm:ss'),
        releaseStatus: type === 'save' ? 0 : 1,
        articlePictureList: articlePictureList.map((item: any) => ({
            name: item.name,
            url: item.response ? item.response.data : item.url
        }))
    }
    // 文章添加
    httpUpdateArticle(<ArticleDetail>updateParams).then(({ success }) => {
        if (success) {
            ElMessages.success('修改成功！')
            cancel()
        } else {
            ElMessages.warning('修改失败！请重试')
        }
    })
}

</script>

<style lang="less" scoped>
.join-member-wrapper {
    width: calc(50% - 12px);

    .el-form {
        &:first-child {

            .el-form-item {
                @apply mt-20;
            }
        }
    }

    .el-form-item {
        @apply mt-34;
    }
}

.sale-box{
    height: 120px;

    .sale-box-left{
        width: 100px;
    }

    .sale-box-top {
        @apply mb-12;
    }

    .sale-box-top, .sale-box-middle, .sale-box-bottom {
        height: 40px;
        @apply flex items-center;
    }
}
</style>
